<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\User;
use app\admin\model\Admin as AdminModel;
use app\admin\model\scanwork\Config as ConfigModel;
use think\Db;
use think\Exception;

/**
 * 微信用户绑定控制器
 */
class WechatBind extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 微信小程序登录
     */
    public function miniprogramLogin()
    {
        $code = $this->request->post('code');
        $userInfo = $this->request->post('userInfo', []);
        
        if (!$code) {
            $this->error('缺少微信授权码');
        }

        try {
            // 微信小程序配置
            $appid = ConfigModel::getMiniappAppid();
            $secret = ConfigModel::getMiniappSecret();
            
            // 获取微信openid
            $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$secret}&js_code={$code}&grant_type=authorization_code";
            $result = file_get_contents($url);
            $data = json_decode($result, true);
            
            if (isset($data['errcode'])) {
                $this->error('微信授权失败：' . $data['errmsg']);
            }
            
            $openid = $data['openid'];
            $session_key = $data['session_key'];
            $unionid = $data['unionid'] ?? '';
            
            // 查找是否已有绑定微信的用户
            $user = User::where('wechat_openid', $openid)->find();
            
            if ($user) {
                // 已绑定，直接登录
                $token = $this->generateToken($user->id);
                $this->success('登录成功', [
                    'token' => $token,
                    'user' => $user,
                    'bind_status' => 'bound', // 已绑定
                    'need_bind' => false
                ]);
            } else {
                // 未绑定，返回需要绑定的状态
                $this->success('需要绑定账号', [
                    'openid' => $openid,
                    'unionid' => $unionid,
                    'session_key' => $session_key,
                    'userInfo' => $userInfo,
                    'bind_status' => 'unbound', // 未绑定
                    'need_bind' => true
                ]);
            }
            
        } catch (Exception $e) {
            $this->error('登录失败：' . $e->getMessage());
        }
    }

    /**
     * 绑定现有用户账号
     */
    public function bindExistingUser()
    {
        $openid = $this->request->post('openid');
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $userInfo = $this->request->post('userInfo', []);
        
        if (!$openid || !$username || !$password) {
            $this->error('参数不完整');
        }
        
        try {
            // 验证用户名和密码
            $user = User::where('username', $username)->find();
            if (!$user) {
                $this->error('用户名不存在');
            }
            
            // 验证密码
            if (md5(md5($password) . $user->salt) !== $user->password) {
                $this->error('密码错误');
            }
            
            // 检查该用户是否已绑定其他微信账号
            if (!empty($user->wechat_openid) && $user->wechat_openid !== $openid) {
                $this->error('该账号已绑定其他微信账号');
            }
            
            // 检查该微信是否已绑定其他账号
            $existingBind = User::where('wechat_openid', $openid)->find();
            if ($existingBind && $existingBind->id !== $user->id) {
                $this->error('该微信账号已绑定其他用户');
            }
            
            Db::startTrans();
            try {
                // 绑定微信账号
                $user->wechat_openid = $openid;
                $user->wechat_unionid = $this->request->post('unionid', '');
                
                // 更新微信用户信息
                if (!empty($userInfo)) {
                    if (empty($user->nickname) || $user->nickname === $user->username) {
                        $user->nickname = $userInfo['nickName'] ?? $user->nickname;
                    }
                    if (empty($user->avatar)) {
                        $user->avatar = $userInfo['avatarUrl'] ?? $user->avatar;
                    }
                }
                
                $user->save();
                
                // 生成token
                $token = $this->generateToken($user->id);
                
                Db::commit();
                
                $this->success('绑定成功', [
                    'token' => $token,
                    'user' => $user,
                    'bind_status' => 'bound'
                ]);
                
            } catch (Exception $e) {
                Db::rollback();
                $this->error('绑定失败：' . $e->getMessage());
            }
            
        } catch (Exception $e) {
            $this->error('绑定失败：' . $e->getMessage());
        }
    }

    /**
     * 创建新用户并绑定
     */
    public function createAndBindUser()
    {
        $openid = $this->request->post('openid');
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email', '');
        $mobile = $this->request->post('mobile', '');
        $userInfo = $this->request->post('userInfo', []);
        
        if (!$openid || !$username || !$password) {
            $this->error('参数不完整');
        }
        
        try {
            // 验证用户名是否已存在
            $existingUser = User::where('username', $username)->find();
            if ($existingUser) {
                $this->error('用户名已存在');
            }
            
            // 验证邮箱是否已存在
            if (!empty($email)) {
                $existingEmail = User::where('email', $email)->find();
                if ($existingEmail) {
                    $this->error('邮箱已被使用');
                }
            }
            
            // 验证手机号是否已存在
            if (!empty($mobile)) {
                $existingMobile = User::where('mobile', $mobile)->find();
                if ($existingMobile) {
                    $this->error('手机号已被使用');
                }
            }
            
            // 检查该微信是否已绑定其他账号
            $existingBind = User::where('wechat_openid', $openid)->find();
            if ($existingBind) {
                $this->error('该微信账号已绑定其他用户');
            }
            
            Db::startTrans();
            try {
                // 生成密码盐
                $salt = \fast\Random::alnum();
                
                // 创建新用户
                $userData = [
                    'group_id' => 1, // 默认用户组
                    'username' => $username,
                    'nickname' => $userInfo['nickName'] ?? $username,
                    'password' => md5(md5($password) . $salt),
                    'salt' => $salt,
                    'email' => $email,
                    'mobile' => $mobile,
                    'avatar' => $userInfo['avatarUrl'] ?? '',
                    'wechat_openid' => $openid,
                    'wechat_unionid' => $this->request->post('unionid', ''),
                    'status' => 'normal',
                    'createtime' => time(),
                    'updatetime' => time()
                ];
                
                $user = User::create($userData);
                
                // 生成token
                $token = $this->generateToken($user->id);
                
                Db::commit();
                
                $this->success('创建并绑定成功', [
                    'token' => $token,
                    'user' => $user,
                    'bind_status' => 'bound'
                ]);
                
            } catch (Exception $e) {
                Db::rollback();
                $this->error('创建失败：' . $e->getMessage());
            }
            
        } catch (Exception $e) {
            $this->error('创建失败：' . $e->getMessage());
        }
    }

    /**
     * 解除微信绑定
     */
    public function unbindWechat()
    {
        if (!$this->auth->isLogin()) {
            $this->error('请先登录');
        }
        
        $user = $this->auth->getUserinfo();
        
        try {
            $userModel = User::find($user['id']);
            if (!$userModel) {
                $this->error('用户不存在');
            }
            
            // 解除绑定
            $userModel->wechat_openid = '';
            $userModel->wechat_unionid = '';
            $userModel->save();
            
            $this->success('解除绑定成功');
            
        } catch (Exception $e) {
            $this->error('解除绑定失败：' . $e->getMessage());
        }
    }

    /**
     * 获取绑定状态
     */
    public function getBindStatus()
    {
        if (!$this->auth->isLogin()) {
            $this->error('请先登录');
        }
        
        $user = $this->auth->getUserinfo();
        
        $userModel = User::find($user['id']);
        if (!$userModel) {
            $this->error('用户不存在');
        }
        
        $this->success('获取成功', [
            'is_wechat_bound' => !empty($userModel->wechat_openid),
            'wechat_openid' => $userModel->wechat_openid,
            'wechat_unionid' => $userModel->wechat_unionid
        ]);
    }

    /**
     * 管理员绑定微信
     */
    public function bindAdminWechat()
    {
        $openid = $this->request->post('openid');
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $userInfo = $this->request->post('userInfo', []);
        
        if (!$openid || !$username || !$password) {
            $this->error('参数不完整');
        }
        
        try {
            // 验证管理员账号
            $admin = AdminModel::where('username', $username)->find();
            if (!$admin) {
                $this->error('管理员账号不存在');
            }
            
            // 验证密码
            if (md5(md5($password) . $admin->salt) !== $admin->password) {
                $this->error('密码错误');
            }
            
            // 检查该微信是否已绑定其他管理员
            $existingBind = AdminModel::where('wechat_openid', $openid)->find();
            if ($existingBind && $existingBind->id !== $admin->id) {
                $this->error('该微信账号已绑定其他管理员');
            }
            
            Db::startTrans();
            try {
                // 绑定微信账号
                $admin->wechat_openid = $openid;
                $admin->wechat_unionid = $this->request->post('unionid', '');
                
                // 更新微信用户信息
                if (!empty($userInfo)) {
                    if (empty($admin->nickname) || $admin->nickname === $admin->username) {
                        $admin->nickname = $userInfo['nickName'] ?? $admin->nickname;
                    }
                    if (empty($admin->avatar)) {
                        $admin->avatar = $userInfo['avatarUrl'] ?? $admin->avatar;
                    }
                }
                
                $admin->save();
                
                // 生成管理员token
                $token = md5($admin->id . time() . rand(1000, 9999));
                session('admin_token', $token);
                session('admin_info', [
                    'id' => $admin->id,
                    'username' => $admin->username,
                    'nickname' => $admin->nickname,
                    'avatar' => $admin->avatar,
                    'is_admin' => true
                ]);
                
                Db::commit();
                
                $this->success('管理员绑定成功', [
                    'token' => $token,
                    'admin_info' => [
                        'id' => $admin->id,
                        'username' => $admin->username,
                        'nickname' => $admin->nickname,
                        'avatar' => $admin->avatar
                    ]
                ]);
                
            } catch (Exception $e) {
                Db::rollback();
                $this->error('绑定失败：' . $e->getMessage());
            }
            
        } catch (Exception $e) {
            $this->error('绑定失败：' . $e->getMessage());
        }
    }

    /**
     * 生成用户token
     */
    private function generateToken($userId)
    {
        $token = \fast\Random::alnum(32);
        \app\common\library\Token::set($token, $userId);
        return $token;
    }

    /**
     * 获取用户列表（用于绑定选择）
     */
    public function getUserList()
    {
        $keyword = $this->request->get('keyword', '');
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);
        
        $where = [];
        if (!empty($keyword)) {
            $where[] = ['username|nickname|mobile|email', 'like', "%{$keyword}%"];
        }
        
        // 只显示未绑定微信的用户
        $where[] = ['wechat_openid', '=', ''];
        
        $list = User::where($where)
            ->field('id,username,nickname,mobile,email,createtime')
            ->order('id desc')
            ->paginate($limit, false, ['page' => $page]);
        
        $this->success('获取成功', [
            'list' => $list->items(),
            'total' => $list->total(),
            'page' => $page,
            'limit' => $limit
        ]);
    }

    /**
     * 同步用户信息
     */
    public function syncUserInfo()
    {
        if (!$this->auth->isLogin()) {
            $this->error('请先登录');
        }
        
        $user = $this->auth->getUserinfo();
        $userInfo = $this->request->post('userInfo', []);
        
        if (empty($userInfo)) {
            $this->error('用户信息不能为空');
        }
        
        try {
            $userModel = User::find($user['id']);
            if (!$userModel) {
                $this->error('用户不存在');
            }
            
            // 更新用户信息
            $updateData = [];
            
            if (!empty($userInfo['nickName']) && (empty($userModel->nickname) || $userModel->nickname === $userModel->username)) {
                $updateData['nickname'] = $userInfo['nickName'];
            }
            
            if (!empty($userInfo['avatarUrl']) && empty($userModel->avatar)) {
                $updateData['avatar'] = $userInfo['avatarUrl'];
            }
            
            if (!empty($updateData)) {
                $userModel->save($updateData);
            }
            
            $this->success('同步成功');
            
        } catch (Exception $e) {
            $this->error('同步失败：' . $e->getMessage());
        }
    }
}
